import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {
    Row,
    Col,
    Card,
    Form,
    Input,
    Select,
    Button,
    Modal,
    Tabs,
    message
} from 'antd';
 import ShippingList from '../../components/shipping/index';

import SellerList from '../../components/shipping/seller/index';
 import ShippingEdit from '../../components/shipping/ShippingEdit';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from './Shipping.less'
import {powerControl} from '../../utils/powerControl';
const AuthButton = powerControl(Button);
const TabPane = Tabs.TabPane;
const FormItem = Form.Item;
 const {Option} = Select;
 const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

 @connect(state => ({
     rule: state.shipping
 }))
@Form.create()
export default class Shipping extends PureComponent{

    state = {
        modalVisible: false,
        editType: 'add',
        formValues: {},
        record: {},
        selectedRows: [],
    };

    componentDidMount(){
        const {dispatch} = this.props;
        dispatch({
            type: 'shipping/fetch',
        });
    }

     handleAddType = () => {
         this.handleModalVisible(true);
         this.setState({
             editType: 'add',
         });
     }

    handleModalVisible = (flag) => {
        this.setState({
            modalVisible: !!flag,
        });
    }

     handleModalSuccess = (pagination) => {
         const {dispatch} = this.props;
         const {formValues} = this.state;
         const params = {
             currentPage: pagination.current,
             pageSize: pagination.pageSize,
             ...formValues,
         };
         dispatch({
             type: 'shipping/fetch',
             payload: params,
         });
     }

     handleShippingListChange = (pagination, filtersArg, sorter) => {
         const {dispatch} = this.props;
         const {formValues} = this.state;

         const filters = Object.keys(filtersArg).reduce((obj, key) => {
             const newObj = {...obj};
             newObj[key] = getValue(filtersArg[key]);
             return newObj;
         }, {});

         const params = {
             currentPage: pagination.current,
             pageSize: pagination.pageSize,
             ...formValues,
             ...filters,
         };
         if (sorter.field) {
             params.sorter = `${sorter.field}_${sorter.order}`;
         }

         dispatch({
             type: 'shipping/fetch',
             payload: params,
         });
     }
     handleSellerListChange = (pagination) => {
         const {dispatch} = this.props;
         const {formValues} = this.state;

         const params = {
             currentPage: pagination.current,
             pageSize: pagination.pageSize,
             ...formValues,
         };

         dispatch({
             type: 'shipping/fetchSeller',
             payload: params,
         });
     }

    handleFormReset = () => {
        const {form, dispatch} = this.props;
        form.resetFields();
        // dispatch({
        //     type: 'shipping/fetch',
        //     payload: {},
        // });
        // this.setState({
        //     formValues: {},
        // });
    }

     handleTempletSearch = (e) => {
         e.preventDefault();
         const {dispatch, form} = this.props;
         form.validateFields((err, fieldsValue) => {
             if (err) return;

             const values = {
                 ...fieldsValue,
                 updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
             };

             this.setState({
                 formValues: values,
             });
             dispatch({
                 type: 'shipping/Sellerfetch',
                 payload: values,
             });
         });
     }


    handleSearch = (e) => {
        e.preventDefault();
        const {dispatch, form} = this.props;
        form.validateFields((err, fieldsValue) => {
            if (err) return;
            const values = {
                ...fieldsValue,
                updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
            };
            this.setState({
                formValues: values,
            });
            dispatch({
                type: 'shipping/fetch',
                payload: values,
            });
        });
    }

     handleAdd = () => {
         this.props.dispatch({
             type: 'shipping/add',
             payload: {
                 description: this.state.addInputValue,
             },
         });
         message.success('添加成功');
         this.setState({
             modalVisible: false,
         });
     }

     handleEditTypeRow = (record, pagination) => {
         this.handleModalVisible(true);
         this.setState({
             editType: 'mod',
             record: record
         });
     }

     handleUpdateStatusRow = (shipping_templet_id,shipping_templet_status, pagination) => {
         const {dispatch} = this.props;
         dispatch({
             type: 'shipping/modSellerShippingStatus',
             payload: {shipping_templet_id: shipping_templet_id,
                 shipping_templet_status:shipping_templet_status
             },
             callback: (response) => {
                 if (response.result === 0) {
                     message.success('更新成功');
                     this.handleModalSuccess(pagination);
                     dispatch({
                         type: 'shipping/Sellerfetch',
                     });
                 } else {
                     message.success('更新失败');
                 }
             }
         });
     }


     handleDelTypeRow = (shipping_id, pagination) => {
         const {dispatch} = this.props;
         dispatch({
             type: 'shipping/delShippingTempletAttr',
             payload: {shipping_id: shipping_id},
             callback: (response) => {
                 if (response.result === 0) {
                     message.success('删除成功');
                     this.handleModalSuccess(pagination);
                 } else {
                     message.success('删除失败');
                 }
             }
         });
     }

     handleSelectRows = (rows) => {
         this.setState({
             selectedRows: rows,
         });
     }

     handleTabChange = (key) => {

         const {dispatch}= this.props;

         if (key == 'shipping') {
             const {dispatch} = this.props;
             dispatch({
                 type: 'shipping/fetch',
             });
         }

         if (key == 'seller') {
             const {dispatch} = this.props;
             dispatch({
                 type: 'shipping/Sellerfetch',
             });
         }
     }
     renderTempletForm() {
         const {getFieldDecorator} = this.props.form;
         return (
             <Form onSubmit={this.handleTempletSearch} layout="inline">
                 <Row gutter={{md: 8, lg: 24, xl: 48}}>
                     <Col md={8} sm={24}>
                         <FormItem label="店铺名称">
                             {getFieldDecorator('shop_name')(
                                 <Input placeholder="请输入"/>
                             )}
                         </FormItem>
                     </Col>
                     <Col md={8} sm={24}>
                         <FormItem label="模板名称">
                             {getFieldDecorator('shipping_templet_name')(
                                 <Input placeholder="请输入"/>
                             )}
                         </FormItem>
                     </Col>
                     <Col md={8} sm={24}>
                        <span className={styles.sumbitButtons}>
                          <AuthButton auth="shipping.search" type="primary" htmlType="submit">查询</AuthButton>
                          <AuthButton auth="shipping.reset" style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</AuthButton>
                        </span>
                     </Col>
                 </Row>
             </Form>
         );
     }

     renderSimpleForm() {
        const {getFieldDecorator} = this.props.form;
        return (
            <Form onSubmit={this.handleSearch} layout="inline">
                <Row gutter={{md: 8, lg: 24, xl: 48}}>
                    <Col md={8} sm={24}>
                        <FormItem label="配送方式编码">
                            {getFieldDecorator('shipping_code')(
                                <Input placeholder="请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <FormItem label="配送方式名称">
                            {getFieldDecorator('shipping_name')(
                                <Input placeholder="请输入"/>
                            )}
                        </FormItem>
                    </Col>
                    <Col md={8} sm={24}>
                        <span className={styles.sumbitButtons}>
                          <AuthButton auth="shipping.search" type="primary" htmlType="submit">查询</AuthButton>
                          <AuthButton auth="shipping.reset" style={{marginLeft: 8}} onClick={this.handleFormReset}>重置</AuthButton>
                        </span>
                    </Col>
                </Row>
            </Form>
        );
    }

    renderForm() {
        return this.renderSimpleForm();
    }

    render() {

         const {modalVisible,editType,record,selectedRows} = this.state;
         const {rule: {loading: ruleLoading, data, typesSList}} = this.props;

        return (
            <PageHeaderLayout title="物流管理">
                <Card bordered={false}>
                    <Tabs onChange={this.handleTabChange} type="card">
                        <TabPane tab="配送方式" key="shipping">
                            <div className={styles.tableList}>
                                <div className={styles.tableListForm}>
                                    {this.renderForm()}
                                </div>
                                <div className={styles.tableListOperator}>
                                    <AuthButton auth="shipping.new" icon="plus" type="primary" onClick={() => this.handleAddType()}>新建</AuthButton>
                                </div>
                                <ShippingList
                                    selectedRows={selectedRows}
                                    loading={ruleLoading}
                                    data={data}
                                    onSelectRow={this.handleSelectRows}
                                    onChange={this.handleShippingListChange}
                                    onDelRow={this.handleDelTypeRow}
                                    onEditRow={this.handleEditTypeRow}
                                />
                            </div>
                        </TabPane>
                        <TabPane tab="运费管理" key="seller">
                            <div className={styles.tableList}>
                                <div className={styles.tableListForm}>
                                    {this.renderTempletForm()}
                                </div>
                            <SellerList
                                selectedRows={selectedRows}
                                loading={ruleLoading}
                                data={data}
                                onSelectRow={this.handleSelectRows}
                                onChange={this.handleSellerListChange}
                                onUpdateRow={this.handleUpdateStatusRow}
                                onEditRow={this.handleEditTypeRow}
                            />
                            </div>
                        </TabPane>
                    </Tabs>


                </Card>
                <Modal
                    title="新增配送方式"
                    key={new Date()}
                    visible={modalVisible}
                    onOk={this.handleAdd}
                    onCancel={() => this.handleModalVisible()}
                    footer={null}
                >
                    <ShippingEdit  ref="shippingEdit"
                                    pagination={data.pagination}
                                    editType={editType}
                                    record={record}
                                    categorySList={typesSList}
                                    handleModalVisible={this.handleModalVisible}
                                    handleModalSuccess={this.handleModalSuccess}/>
                </Modal>
            </PageHeaderLayout>
        );
    }
}